﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Collections;

/// <summary>
/// DataOperation 资料操作相关类
/// </summary>
public class DataOperation
{
    public string DataType;
    public string DataID;
    public string Title;
    public string SubTitle;
    public int FlowSubTypeID;
    public string UserName;
    public DateTime WriteDate;
    public string FilesName;
    public string FilesPath;
    public DateTime AddTime;
    public string Brief;
    public string Status;
    public int FlowMID;
    public int DEPID;
    public string AttachFiles;
    public string FlowStatus;
    private string _dataTablePrefix = "DATA";

    public DataOperation()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
    public DataOperation(string tempDataId)
    {
        string theYear = tempDataId.Substring(2, 4);
        string sqlString = "select * from DATA" + theYear + " where DATAID='" + tempDataId + "'";
        DBOperation DBO = new DBOperation();
        SqlDataReader sdr = DBO.GetDataReader(sqlString);
        if (sdr.Read())
        {
            this.DataType = sdr["FLOWTYPEMARK"].ToString();
            this.DataID = tempDataId;
            this.DEPID = Convert.ToInt32(sdr["DEPID"].ToString());
            this.FilesPath = sdr["FILESPATH"].ToString();
            this.FlowSubTypeID = Convert.ToInt32(sdr["FLOWSUBTYPEID"].ToString());
            this.Status = sdr["STATUS"].ToString();
            this.SubTitle = sdr["SUBTITLE"].ToString();
            this.Title = sdr["TITLE"].ToString();
            this.UserName = sdr["USERNAME"].ToString();
            this.Brief = sdr["BRIEF"].ToString();
            this.WriteDate = Convert.ToDateTime(sdr["WRITEDATE"].ToString());
            //this.AddTime = Convert.ToDateTime(sdr["ADDDATE"].ToString());
            
        }
        sdr.Close();
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>
    /// 添加记录的方法
    /// </summary>
    /// <returns>成功则返回True，否则返回False</returns>
    public Boolean AddData()
    {
        try
        {
            this.DataID = CreateDataID(this.WriteDate.Year.ToString(), this.WriteDate.Month.ToString(), this.DataType);
            string tableName = this._dataTablePrefix+ this.WriteDate.Year.ToString();
            BasicClass BC = new BasicClass();
            this.DEPID = Convert.ToInt32(BC.GetDepIDByUserName(this.UserName));
            string sqlString = "insert into " + tableName + " (DATAID,TITLE,SUBTITLE,FLOWSUBTYPEID,WRITEDATE,DEPID,USERNAME,FILESPATH,BRIEF,STATUS,FLOWTYPEMARK,ADDDATE) values ('";
            sqlString += this.DataID + "','" + this.Title + "','" + this.SubTitle + "'," + this.FlowSubTypeID + ",'" + this.WriteDate.ToString() + "',"+this.DEPID.ToString()+",'" + this.UserName + "','" + this.FilesPath + "','" + this.Brief + "','0','"+this.DataType+"','"+DateTime.Now.ToString()+"')";
            DBOperation DBO = new DBOperation();
            if (DBO.ExcuteSql(sqlString))
            {
                CreateFlow();
                AddAnnexFiles();
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
 
    }
    //产生流程
    private void CreateFlow()
    {
        string tableName = "LC" + this.WriteDate.Year.ToString();
        string trueFlowID = "LC" + DataID;
        string sQuerystring = "insert into "+tableName+" (TRUEFLOWID,FLOWMID,DATAID,CURRENTSTEP,STATUS,BRIEF) values ('";
        sQuerystring += trueFlowID + "'," + this.FlowMID.ToString() + ",'" + this.DataID + "',1,'" + this.FlowStatus +"','" + this.Brief + "')";
        DBOperation DBO = new DBOperation();
        if (DBO.ExcuteSql(sQuerystring))
        {
            //if (this.FlowStatus != "1")
            //{
                CreateFlowSteps(trueFlowID);
            //}
        }
    }
    //产生流程步骤
    private void CreateFlowSteps(string trueFlowID)
    {        
        string insertTable = "LCBZ" + this.WriteDate.Year.ToString();
        string sQueryString = "select * from LCBZMINFO where FLOWMID=" + this.FlowMID.ToString() + " order by SEQ ASC";
        DBOperation DBO = new DBOperation();
        SqlDataReader sdr = DBO.GetDataReader(sQueryString);
        while (sdr.Read())
        {
            string tempQueryString = "";
            if (this.FlowStatus == "0")
            {

                tempQueryString = "insert into " + insertTable + " (TRUEFLOWID,SEQ,OPERATORID,DEPID,CONTENT,STATUS) values ('";
                tempQueryString += trueFlowID + "'," + sdr["SEQ"].ToString() + ",'" + sdr["USERIDLIST"].ToString() + "'," + sdr["DEPID"].ToString() + ",'" + sdr["CONTENT"].ToString() + "','0')";
                if (Convert.ToInt32(sdr["SEQ"].ToString()) == 1)
                {
                    SendMessage(trueFlowID, this.UserName, sdr["USERIDLIST"].ToString());
                }
            }
            else
            {
                tempQueryString = "insert into " + insertTable + " (TRUEFLOWID,SEQ,OPERATORID,DEPID,CONTENT,STATUS,ATTITUDE,ANNOTATE,BEGINDATE,ENDDATE) values ('";
                tempQueryString += trueFlowID + "'," + sdr["SEQ"].ToString() + ",'" + sdr["USERIDLIST"].ToString() + "'," + sdr["DEPID"].ToString() + ",'" + sdr["CONTENT"].ToString() + "','1','通过','通过','" + this.WriteDate.ToString() + "','" + this.WriteDate.ToString() + "')";

            }
            DBO.ExcuteSql(tempQueryString);
            
            
        }
        sdr.Close();
    }
    //发送消息，测试用，要转移到MESSAGE类
    protected Boolean SendMessage(string trueFlowID, string fromUserName, string toUserName)
    {
           
        string title = "您有新的文件需要审批了！";
        string content = "您有新的文件需要审批了！流程号:" + trueFlowID+"。"+"文件简介："+this.Brief;
        messages sendMS = new messages();
        sendMS.FromUserName=fromUserName;
        sendMS.ToUserName=toUserName;
        sendMS.TrueFlowID=trueFlowID;
        sendMS.Title=title;
        sendMS.Content=content;
        if (sendMS.SendCheckDataMessage())
        {
            return true;
        }
        return false;
    }
    
    //生成资料ID
    public string CreateDataID(string strYear, string strMonth, string DataType)
    {
        if (strMonth.Length == 1)
        {
            strMonth = "0" + strMonth;
        }
        string prefixString = DataType + strYear + strMonth;
        string tableName = this._dataTablePrefix+ strYear;
        string LastItemDataID = "0000";
        string DataFlowID = "";
        DBOperation DBO = new DBOperation();
        //判断本月是否保存过文件，若有则取出最后一个添加的文件的文件编号：DATAID
        string sQueryString = "select DATAID from "+tableName+" where DATAID like '" + prefixString + "%' order by AUTOID desc";
        SqlDataReader sdr = DBO.GetDataReader(sQueryString);
        if (sdr.Read())
        {
            LastItemDataID = sdr[0].ToString();
        }
        //取得流水号整数部分
        DataFlowID = LastItemDataID.Substring(LastItemDataID.Length - 4);
        while (DataFlowID.Substring(0, 1).ToString() == "0")
        {
            DataFlowID = DataFlowID.Substring(1);
            if (DataFlowID.Length == 1)
            {
                break;
            }
        }
        //将流水号加1,并将流水号不足四位
        DataFlowID = Convert.ToString(Convert.ToInt32(DataFlowID) + 1);
        int len = DataFlowID.Length;
        if (len < 4)
            for (int j = 0; j <= 4 - len - 1; j++)
            {
                DataFlowID = "0" + DataFlowID;
            }

        string DataID = prefixString + DataFlowID;
        sdr.Close();
        return DataID;
        
    }
    /// <summary>
    /// 判断资料文件存放的目录是否存在
    /// </summary>
    /// <param name="DataType">资料类型</param>
    /// <returns></returns>
    public string CheckDirectory(string DataType)
    {
        string currentYear = DateTime.Now.Year.ToString();
        string currentMonth = DateTime.Now.Month.ToString();
        if (currentMonth.Length == 1)
        {
            currentMonth = "0" + currentMonth;
        }
        string fileDir = currentYear + currentMonth;
        string savePath = "\\" + DataType;
        string Dirpath = HttpContext.Current.Server.MapPath("files") + savePath;

        if (!Directory.Exists(Dirpath))
        {
            Directory.CreateDirectory(Dirpath);
        }
        savePath += "\\" + fileDir;
        Dirpath += "\\" + fileDir;
        if(!Directory.Exists(Dirpath))
        {
            Directory.CreateDirectory(Dirpath);
        }
        return savePath;        
        
    }
    public string GetFilesPathByDataID(string dataid)
    {
        string dataIdPrefix = dataid.Substring(0, 2);
        string theYear = dataid.Substring(2, 4);
        //Hashtable tempHstab = BasicClass.GetTabPrefixAndDataIDHashTab();
        //string tablePrefix = tempHstab[dataIdPrefix].ToString();
        string tableName = "DATA" + theYear;
        string sqlString = "select FILESPATH from " + tableName + " where DATAID='" + dataid + "'";
        DBOperation DBO = new DBOperation();
        string filepath = DBO.ExcuteScalar(sqlString).ToString();
        return filepath;       
 
    }
    /// <summary>
    /// 将附件信息写入数据库
    /// </summary>
    /// <returns></returns>
    public Boolean AddAnnexFiles()
    {
        Boolean success = false;
        string tableName = "ATTACHFILES" + WriteDate.Year.ToString();
        string[] FilePaths = new string[20];
        char[] separator ={ ',' };
        FilePaths = this.AttachFiles.Split(separator);
        try
        {
            for (int i = 0; i < FilePaths.Length; i++)
            {
                if (FilePaths[i] != "")
                {
                    string insertSqlString = "insert " + tableName + " (DATAID,FILEPATH) values ('" + this.DataID+ "','" + FilePaths[i].ToString() + "')";
                    DBOperation DBO = new DBOperation();
                    DBO.ExcuteSql(insertSqlString);
                }
            }
            success = true;
        }
        catch (Exception ex)
        {
            string exMsg = ex.Message.ToString();
            success = false;
        }
        return success;
    }
    /// <summary>
    /// 根据资料编号DATAID获取附件路径集合
    /// </summary>
    /// <param name="DATAID">资料编号</param>
    /// <returns>返回存储了所有附件路径的Hashtable</returns>

    public Hashtable GetAnnexFiles(string DATAID)
    {
        Hashtable annexFiles = new Hashtable();
        string dataYear = DATAID.Substring(2, 4);
        string tableName = "ATTACHFILES" + dataYear;
        string sqlString = "select * from " + tableName + " where DATAID='" + DATAID + "'";
        DBOperation DBO = new DBOperation();
        SqlDataReader sdr = DBO.GetDataReader(sqlString);

        for (int i = 0; sdr.Read(); i++)
        {
            annexFiles[i] = sdr["FILEPATH"].ToString();
        }
        sdr.Close();
        return annexFiles;
    }

    /// <summary>
    /// 获取资料提交人的真实姓名
    /// </summary>
    /// <param name="DataId">资料编号</param>
    /// <returns>资料提交人的真实姓名</returns>
    public static string GetWriterByDataID(string DataId)
    {
        string theYear = DataId.Substring(2, 4);
        string dataTableName="DATA"+theYear;
        string sqlString = "select USERS.TRUENAME from USERS inner join " + dataTableName + " as Data on USERS.USERNAME=Data.USERNAME where DATAID='" + DataId + "'";
        DBOperation DBO = new DBOperation();
        string tempUserName = DBO.ExcuteScalar(sqlString).ToString();
        return tempUserName;
    }
    public static string GetCurrentOperatorByDataID(string DataId)
    {
        string theYear = DataId.Substring(2, 4);
        string sqlString = "select LCBZ.OPERATORID from LCBZ" + theYear + " as LCBZ inner join LC" + theYear + " as LC on LCBZ.SEQ=LC.CURRENTSTEP and LC.TRUEFLOWID=LCBZ.TRUEFLOWID where LC.STATUS='0' and LC.DATAID='" + DataId + "'";
        DBOperation DBO = new DBOperation();
        string currentOperatoUserName = "";
        string trueName = "";
        if (DBO.ExcuteScalar(sqlString) != null)
        {
            currentOperatoUserName = DBO.ExcuteScalar(sqlString).ToString();
            trueName = BasicClass.GetTrueNameByUserName(currentOperatoUserName);
        }
        return trueName;
    }
    public Boolean DelData(string tempDataId,string prefixPath)
    {
        //File.Delete(prefixPath+"/abc.txt");
        bool success = false;
        string theYear = tempDataId.Substring(2, 4);
        string sqlString = "select FILESPATH from DATA" + theYear + " where DATAID='" + tempDataId + "'";
        string sqlStringAttachFiles = "select FILEPATH from ATTACHFILES" + theYear + " where DATAID='" + tempDataId + "'";
        DBOperation DBO = new DBOperation();
        SqlDataReader sdr = DBO.GetDataReader(sqlString);
        string tempFilePath = prefixPath;
        try
        {
            while (sdr.Read())
            {
                tempFilePath = prefixPath;
                tempFilePath += sdr["FILESPATH"].ToString();
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }

            }
            sdr.Close();            
            SqlDataReader sdr2 = DBO.GetDataReader(sqlStringAttachFiles);
            while (sdr2.Read())
            {
                tempFilePath = prefixPath;
                tempFilePath += sdr2["FILEPATH"].ToString();
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }

            }
            sdr2.Close();
            ArrayList delDataSqls = new ArrayList();
            delDataSqls.Add("delete from DATA" + theYear + " where DATAID='" + tempDataId + "'");
            delDataSqls.Add("delete from ATTACHFILES" + theYear + " where DATAID='" + tempDataId + "'");
            delDataSqls.Add("delete from LC" + theYear + " where DATAID='" + tempDataId + "'");
            delDataSqls.Add("delete from LCBZ" + theYear + " where TRUEFLOWID='LC" + tempDataId + "'");
            DBO.ExcuteSqls(delDataSqls);
            success= true;
        }
        catch(Exception e)
        {
            string ex = e.Message.ToString();
            success = false;
        }
        return success;
    }
}
